package server.business.login;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import server.ScriptEnum;
import server.ServerEngin;
import server.ServerTransportProxy;
import server.commonData.Player;
import server.commonData.Room;
import server.commonData.SqlStatementEnum;
import server.commonData.Table;
import server.commonData.User;
import server.messageId.S2CMessageId;
import server.msgBean.LoginMessage.RefreshMoneyVipGoldRes;
import server.utils.AbsAsyncUpdateDb;

import com.core.initialize.Message;


public class LoginScript implements ILoginScript 
{
	
	@Override
	public Table joinTable(Room room,Player player)
	{
		Table table = room.joinTable(player);
		//将桌子玩家信息发给客户端
		if(player.getType()==Player.USER)
		{
			Message msg = Message.newMessage();
			msg.setModuleAction(S2CMessageId.Login.MODULE_ID, S2CMessageId.Login.ENTER_TABLE);
			msg.setBody(table.showTableInfo());
			ServerTransportProxy.sendMsg(msg, (User)player);
		}
		return table;
	}
	
	@Override
	public void refrechVipMoneyGoldInfo(User user)
	{
		RefreshMoneyVipGoldRes.Builder builder = RefreshMoneyVipGoldRes.newBuilder();
		builder.setYuanbao(user.getYuanbao());
		builder.setVipEndTime(user.getVipEndTime());
		builder.setVipLevel(user.getVipLevel());
		builder.setMoney(user.getMoney());
		Message msg = Message.newMessage();
		msg.setModuleAction(S2CMessageId.Login.MODULE_ID, S2CMessageId.Login.REFRESH_VIP_MONEY_GOLD);
		msg.setBody(builder);
		ServerTransportProxy.sendMsg(msg, user);
	}

	@Override
	public void quiteGame(User user,boolean isSaveDb)
	{
		leftTable(user);
		//下线存库
		if(isSaveDb)
		{
			Map<String, Object> map = new HashMap<String, Object>();
			user.writeToDb(map);
			List params = new ArrayList();
			String sql = SqlStatementEnum.generateReplaceSql(map, params);
			new asyncUpdateDb(sql, params);
		}
		ServerEngin.getInstance().getCache().delUser(user.getId());
	}

	class asyncUpdateDb extends AbsAsyncUpdateDb
	{
		public asyncUpdateDb(String sql, List params) {
			super(sql, params);
		}
		@Override
		protected void updateBack()
		{}
	}
	
	
	@Override
	public int getId() {
		return ScriptEnum.LOGIN_SCRIPT;
	}

	@Override
	public void changeTable(User user) {
		if(user.getTable()==null)
			return;
		Room room = user.getRoom();
		if(room==null)
			return;
		//离开老桌子
		leftTable(user);
		//加入新桌子
		joinTable(room, user);		
	}

	@Override
	public void leftTable(User user) {
		Table table = user.getTable();
		//玩家在桌子上面 计算一些金币
		if(table!=null)
		{
			//判断玩家是否在游戏进行中
			if(table.getStatus()!=ScriptEnum.PLAY_WAIT)
			{
				//掉线或者离线默认扣除5倍金币
				int baseBeilv = user.getRoom().getBeilv();
				user.delMoney(baseBeilv*5);
			}
			user.getRoom().leftTable(user);
		}
	}
}
